﻿using System;
using System.Linq;
using Evpo.ContactData.Common;
using Evpo.ContactData.Data;
using System.Collections.Generic;

namespace Evpo.ContactData.ViewModel
{
    public class AddressListViewModel : ListViewModel
    {
        public AddressListViewModel(
            ModelFactory factory, IConnection conn,
            AddressQueryParameters queryParameters, int pageCount)
            : base(pageCount)
        {
            _addressAdapter = factory.CreateAddressAdapter(conn);
            AddressQuery = queryParameters; 
        }

        #region Fields
        private readonly AddressAdapter _addressAdapter;
        #endregion

        #region Properties
        public override object QueryResultAsDataSource()
        {
            return Addresses();
        }

        public AddressQueryParameters AddressQuery
        {
            get;
            private set;
        }
        
        public override ListQueryParameters ListQuery
        {
            get { return AddressQuery; }
        }

        protected override AdapterBase Adapter
        {
            get { return _addressAdapter; }
        }

        #endregion

        #region Methods
        public List<IAddress> Addresses()
        {
            List<IAddress> retVal = null;
            if (DataSource == null)
            {
                int count;
                retVal =
                    (from address in _addressAdapter.QueryAddresses(AddressQuery, out count)
                     select (IAddress)new Address()
                     {
                         ContactAddressID = address.ContactAddressID,
                         Line1 = address.Line1,
                         Line2 = address.Line2,
                         Suburb = address.Suburb,
                         State = address.State,
                         Postcode = address.Postcode,
                         Country = address.Country,
                     }).ToList();

                this.ItemCount = count;
                DataSource = retVal;
            }

            return retVal;
        }

        
        #endregion Methods
    }
}
